<template>
  <el-upload
    class="upload-demo"
    ref="upload"
    :limit="limit"
    :action="action"
    :accept="fileType"
    :on-preview="downLoad"
    :file-list="fileList"
    :on-remove="removeFilePFormFile"
    :on-change="handleChange"
    :http-request="uploadFilePFormFile"
  >
    <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
  </el-upload>
</template>

<script>
export default {
  name: "fileUpload",
  data() {
    return {
      fileList: [],
    };
  },
  props: {
    isOne: {
      type: Boolean,
      default: false,
    },
    limit: {
      type: Number,
      default: 3,
    },
    action: {
      type: String,
      default: "",
    },
    fileType: {
      type: String,
    },
    fileListPFormFile: {
      type: Array,
      default: [],
    },
    uploadfile: {
      type: Function,
    },
  },
  watch: {},
  computed: {},
  created() {
    this.fileList = this.fileListPFormFile;
  },
  methods: {
    downLoad(file) {
      window.open(file.url);
    },
    removeFilePFormFile(file, fileList) {
      
      // this.fileListPFormFile = fileList;
      this.fileList = fileList;
      //   this.editForm.docPath = fileList;
      this.$emit("removeFile", fileList);
    },
    handleChange(file, fileList) {
      if (this.isOne && fileList && fileList.length >= 2) {
        fileList.splice(0, 1);
        // this.fileList = fileList;
        //  this.fileListPFormFile = fileList;
      }
      
      //   this.fileList = fileList.slice(-3);
    },
    //文件请求上传
    uploadFilePFormFile(param) {
      let _this = this;
      let uploadData = this.getUploadData(param);
      this.uploadfile(uploadData).then((res) => {
        
        if (res != "undefined" && res.length > 0) {
          this.$emit("uploadFileRes", res);
          //   this.pForm.fileName = res[0].name;
          //   this.pForm.filePath = res[0].url;
          let file = {
            name: res[0].name,
            url: res[0].url,
          };
          if (this.isOne) {
            this.$emit("fileListChange", file);
            return;
          }
          this.fileListPFormFile.push(file);
          this.fileList = this.fileListPFormFile;
          this.$emit("fileListChange", this.fileListPFormFile);
          //   this.editForm.docPath = this.fileListPFormFile;
        }
      });
    },
    //获取文件数据添加formdata
    getUploadData(param) {
      let uploadData = new FormData();
      uploadData.append("file", param.file);
      return uploadData;
    },
  },
};
</script>

<style lang="scss" scoped>
// @import "@/styles/element-variables.scss";
</style>
